const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

let entries = {};
let chunks = [];
getEntriesAndChunks();

let config = {
  // entry: {
  //   index:'./src/pages/index.js',
  //   second:'./src/pages/second.js',
  // },
  entry:entries,
  output: {
    filename: './js/[name].bundle.js',
    path: path.resolve(__dirname, './dist'),
    // publicPath:'../'
  },
  resolve: {
      //配置别名，在项目中可缩减引用路径
      extensions: ['.js', '.vue'],
      alias: {
          'lib': path.resolve(__dirname, 'src/lib'),
          // 'vue$': path.resolve(__dirname, 'src/lib/vue.min.js'),
          // 'vue$': path.resolve(__dirname, 'src/lib/vue.js'),
          'vue$': 'vue/dist/vue.esm.js'
      }
  },
  module: {
  	rules: [
  		// {
  		// 	test:/\.css$/,
  		// 	use:[
  		// 		'style-loader',
  		// 		'css-loader'
  		// 	]
  		// },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          // extractCSS: true,
          loaders: {
            scss: 'vue-style-loader!css-loader!sass-loader', // <style lang="scss">
            sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // <style lang="sass">
          }
        }
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      },
      {
        test: require.resolve('jquery'),
        use: [{
            loader: 'expose-loader',
            options: '$'
          },{
            loader: 'expose-loader',
            options: 'jQuery'
        }]
      },
      {
        test: /\.html$/,
        use: [ "html-loader" ]
      },
      {
        test:/\.css$/,
        use:ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        })
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //如果需要，可以在 sass-loader 之前将 resolve-url-loader 链接进来
          use: ['css-loader', 'sass-loader']
        })
      },
      {
        test:/\.(png|jp[e]*g|gif)$/,
        use:[
          {
            loader:'url-loader',
            options: {
              name:'[name].[ext]',
              limit:10000,
              outputPath: './images/'
            }
          }
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
        use: [
           {
            loader:'file-loader',
            options: {
              name:'[name].[ext]',
              outputPath: './font/'
            }
          }
        ]
      }
  	]
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      'window.$': 'jquery',
    }),

    new ExtractTextPlugin({
      filename: './[name].css'
    }),

    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      filename: 'common/common.js',
      chunks: getCommonChunks(chunks),
      minChunks: 2
    }),
    // new webpack.optimize.CommonsChunkPlugin({
    //   name:'common',
    //   minChunks:2//默认数量为入口chunks的数量
    // })
  ]
};

const pages = getHtmls();

pages.forEach(function(pathname) {
    // filename 用文件夹名字

    let fileBasename = pathname.slice(pathname.lastIndexOf('/')+1);
    var conf = {
        filename: './'+pathname + '.html', //生成的html存放路径，相对于path
        template: './src/pages/' + pathname + '.html', //html模板路径
    };
    var chunk = pathname.slice(pathname.lastIndexOf('/')+1);
    if (chunks.indexOf(chunk) > -1) {
        conf.inject = 'body';
        conf.chunks = ['common', chunk];
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

function getHtmls() {
    var htmls = [];
    glob.sync('./src/pages/**/*.html').forEach(function(name) {
        var n = name.slice(name.lastIndexOf('src/pages/')+10, name.length - 5);
        htmls.push(n);
    });

    return htmls;
}

function getEntriesAndChunks() {
    glob.sync('./src/**/*.js').forEach(function(name) {
        if (name.indexOf('lib') > -1){
          return
        }
        var n = name.slice(name.lastIndexOf('/')+1, name.lastIndexOf('.js'));
        // var n = name.slice(name.lastIndexOf('src/') + 10, name.length - 3);
        entries[n] = [name];
        chunks.push(n);
    });
}

function getCommonChunks(chunks) {
    let newChunks = [];
    console.log(chunks)
    chunks.forEach(function(item) {
        if (!item.includes('questions')) {
            newChunks.push(item);
        }
    });
    console.log(newChunks);
    return newChunks;
}
module.exports = config;
